package com.tao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tao.factorys.SubmittableFactory;
import com.tao.pojo.Answerer;
import com.tao.pojo.Miaosha;
import com.tao.service.AnswererService;
import com.tao.service.MiaoshaService;
import com.tao.service.SubmittableService;
import com.tao.service.impl.Mq.MiaoshaSendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: alubus
 * @Date: 2021/11/11 17:06
 * @Package: com.tao.service.impl
 */
@Service
public class MiaoshaServiceImpl implements MiaoshaService {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    RedisTemplate redisTemplate;

//    秒杀Mq请求发送测试
    @Autowired
    MiaoshaSendService miaoshaSendService;

    @Autowired
    SubmittableService submittableService;

    @Resource
    SubmittableFactory submittableFactory;

    @Autowired
    AnswererService answererService;

    private List<Long> miaoshaIds = new ArrayList<>();
//   list.contains(o)  查看是否含有 o

    //设置/重置 秒杀数据
    @Override
    @CacheEvict(value = "miaosha::count",key = "'getMiaoshaValues'")
    public void setMiashaSum(Long id, int sum) {
        redisTemplate.opsForHash().put("miaosha.q", id.toString(), sum);
        if (!miaoshaIds.contains(id)){
            miaoshaIds.add(id);
        }

        logger.info("设置秒杀池 miaosha.q 中，id："+id+"的秒杀总量为："+sum);
    }




//     miaosha.q  的  id 数据减少  sum
    @Override
    public synchronized int reduceMiaoshaSum(Long id, int sum)  {
        Long increment;

//            int miaoshaSum = this.getMiaoshaSum(id);
//            if (miaoshaSum<=0){
//                return -999;
//            }
            increment = redisTemplate.opsForHash().increment("miaosha.q", id.toString(),-sum);

        return Math.toIntExact(increment);
    }

    // redis 中hash值： miaosha.q 的 key：id  的值-1
    @Override
    public synchronized int reduceMiaoshaSumOne(Long id) {
        Long increment;
            increment = redisTemplate.opsForHash().increment("miaosha.q", id.toString(), -1);
        return Math.toIntExact(increment);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int reduceByMq(Long id, int sum) {
        miaoshaSendService.makeOrder();
        return 1;
    }

    @Override//下单到666  submit
    public String StByMs(Long qid) {
        boolean save = submittableService.save(submittableFactory.getSubmittable(qid, 666L));
        return "success";
    }


//    查询 秒杀商品By id
    @Override
    public Answerer selectAnswererByMid(Long mid) {
        Answerer as = answererService.getById(mid);
        if (as==null){
            return null;
        }
        return  answererService.getById(mid);
    }

    /**
     *返回全部的秒杀列表
     * @return
     */
    @Override
    public List<Long> getMiaoshaIds() {
        return this.miaoshaIds;
    }


    @Cacheable(value = "miaosha::count",key = "'getMiaoshaValues'")
    @Override
    public  Map<String,Integer> getMiaoshaValues() {
        Map<String,Integer> map =new HashMap<>();
        this.miaoshaIds.forEach(
                id->{
                    map.put(String.valueOf(id),this.getMiaoshaSum(id));
                }
        );
        return map;
    }

    @Override
    public List<Answerer> getAnswerersByKeys() {
        if (miaoshaIds==null){
            return null;
        }
        QueryWrapper<Answerer> wrapper  = new QueryWrapper<>();
        wrapper.in("id",miaoshaIds);
        wrapper.select(Answerer.class, info -> !info.getColumn().equals("password"));
        return answererService.list(wrapper);
    }

    //获取剩余值
    @Override
    public int getMiaoshaSum(Long id){
        int o=0 ;
        try {
            o= (int) redisTemplate.opsForHash().get("miaosha.q", id.toString());
        } catch (Exception e) {
            logger.error("数据库没有哦："+e.getMessage());
        }
        return o;
    }





}
